# 1. 导入所需库
import pandas as pd
import numpy as np
# import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans

pd.set_option('display.unicode.east_asian_width', True)
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
pd.set_option('max_colwidth', 100)

# 1. 数据加载
df = pd.read_csv("supermarket_customer.csv")               # 1
df["order_date"] = pd.to_datetime(df["order_date"])                  # 2

# 2. 计算RFM指标
benchmark_date = pd.to_datetime("2024-07-01") # 设定基准日期（固定为2024-07-01）  # 3

# 按客户分组计算RFM
rfm = df.groupby("customer_id").agg({                             # 4
    "order_date": lambda x: (benchmark_date - x.max()).days,  # R：最近消费距基准日天数   # 5
    "order_amount": ["count", "sum"]  # F：消费次数，M：总消费金额                  # 6
}).reset_index()

rfm.columns = ["customer_id", "R", "F", "M"]

# 4. 数据标准化
scaler = StandardScaler()                                            # 7
rfm_scaled = scaler.fit_transform(rfm[["R", "F", "M"]])                # 8
# 转换为DataFrame方便查看
rfm_scaled_df = pd.DataFrame(rfm_scaled, columns=["R_scaled", "F_scaled", "M_scaled"])  # 9

k = 4

# 6. K均值聚类
# 构建聚类模型
kmeans_model = KMeans(n_clusters=k, random_state=2024)          # 10
# 给原始RFM数据添加聚类标签
rfm["cluster_label"] = kmeans_model.fit_predict(rfm_scaled)  # 11

# 统计各聚类客户数量及占比
cluster_count = rfm["cluster_label"].value_counts().reset_index()  # 12
cluster_count.columns = ["聚类标签", "客户数量"]
cluster_count["客户占比(%)"] = (cluster_count["客户数量"] / cluster_count["客户数量"].sum() * 100).round(2) # 13
# print("各聚类客户统计：\n", cluster_count)
# print()

# 8. 聚类结果分析
# 计算各聚类R、F、M均值
cluster_mean = rfm.groupby("cluster_label").agg({"R": "mean", "F": "mean", "M": "mean"}).round(2) # 14
cluster_mean.columns = ["平均最近消费天数", "平均消费频率", "平均总消费金额"] # 15
print("各聚类指标均值：\n", cluster_mean)
print()

# 客户分群命名（参考示例，学生可调整）
cluster_names = {
    0: "__________",  # 例：高价值客户（R小、F大、M大）
    1: "__________",  # 例：潜力客户（R小、F小、M大）
    2: "__________",  # 例：一般客户（R中、F中、M中）
    3: "__________"  # 例：低价值客户（R大、F小、M小）
}
# 打印命名结果
for label, name in cluster_names.items():
    print(f"聚类{label}：{name}")
print()

# 运营策略建议（各写1句）
print("高价值客户运营建议：__________")  # 例：发放专属优惠券，提升复购
print("低价值客户运营建议：__________")  # 例：推送新人福利，吸引再次消费
